import s from './Main.module.less'
import { useEffect } from 'react'
import { PageIs, PagesKeys, pages } from './pages'
import classNames from 'classnames'
import { useLocalStorage } from './use-locastorage'
import { stoerKeys } from './store-keys'
import pageStyle from './pages.module.less'

function getHashPage(): PagesKeys | undefined {
  const hash = location.hash.substring(1)
  if (hash in pages) {
    return hash as PagesKeys
  }
  return undefined
}

export function Main() {
  const [page, setPage] = useLocalStorage<PagesKeys>(
    stoerKeys.SELECTED_PAGE,
    () => getHashPage() || 'webrtc'
  )

  useEffect(() => {
    const onHashChange = () => {
      setPage(getHashPage() || 'webrtc')
    }
    window.addEventListener('hashchange', onHashChange)
    return () => {
      window.removeEventListener('hashchange', onHashChange)
    }
  }, [])

  useEffect(() => {
    if (pages[page]) {
      document.title = pages[page].title
    } else {
      setPage('webrtc')
    }
  }, [page, setPage])

  return (
    <div className={s.pages}>
      <div className={s.buttonList}>
        {...(Object.keys(pages) as PagesKeys[]).map((p) => {
          return (
            <button
              key={p}
              onClick={() => setPage(p)}
              className={classNames(
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                ((pageStyle as any)[p] as string) || '',
                s.button,
                p === page && s.selected,
                pages[p].icon
              )}
              title={pages[p].title}
            >
              {pages[p].label}
            </button>
          )
        })}
      </div>
      <PageIs className={s.pageContent} is="webrtc" page={page} />
      <PageIs className={s.pageContent} is="linker" page={page} />
      <PageIs className={s.pageContent} is="logs" page={page} />
      <PageIs className={s.pageContent} is="ui" page={page} />
      <PageIs className={s.pageContent} is="cpp" page={page} />
    </div>
  )
}
